use std::fs;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use crate::builder::Builder;

// mapper 构建
#[derive(Debug)]
pub struct MapperBuilder {
    // 蛛丝
    notes: String,
    // 包名
    package_name: String,
    // 实体包路径
    entity_path: String,
    // 实体名
    entity_name: String,
    // 基础路径
    base_path: String,
}

impl MapperBuilder {

    pub fn new(base_path: &str, notes: &str, entity_path: &str, package_name: &str, entity_name: &str) -> Self {
        MapperBuilder {
            base_path: base_path.to_string(),
            notes: notes.to_string(),
            package_name: package_name.to_string(),
            entity_path: entity_path.to_string(),
            entity_name: entity_name.to_string(),
        }
    }

    fn import_and_package(&self) -> String {
        format!("package {};\n\nimport com.baomidou.mybatisplus.core.mapper.BaseMapper;\nimport {};\n\n",
                self.package_name,
                format!("{}.{}", self.entity_path, self.entity_name)
        )
    }

    fn content(&self) -> String {
        format!(
            "public interface {} extends BaseMapper<{}> {{\n\n}}\n",
            format!("{}Mapper", self.entity_name),
            self.entity_name
        )
    }

}

impl Builder for MapperBuilder {
    fn build(&self) -> String {
        let mut result = String::from("");
        result.push_str(self.import_and_package().as_str());
        result.push_str(self.notes.as_str());
        result.push_str(self.content().as_str());
        result.to_string()
    }

    fn build_file(&self) {
        let parent_path = format!("{}/{}", self.base_path, self.entity_name);
        fs::create_dir_all(Path::new(parent_path.as_str())).unwrap();
        let file_name = format!("{}/{}Mapper.java", parent_path, self.entity_name);
        // println!("{}", file_name);
        let mut file = File::create(file_name).unwrap();
        file.write_all(self.build().as_bytes()).unwrap();
    }
}

#[cfg(test)]
mod tests {

    #[test]
    fn test_build() {}

    #[test]
    fn test_build_file() {}

}